package com.zt.chatgpt.intercepter;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

/**
 * @author: zt
 * @Description: apenAI拦截器，用于拦截请求获取参数并效验
 * @create: 2024-05-10 22:59
 */

public class OpenAiInterceptor implements Interceptor {

    /**
     * OpenAi apiKeyBySystem
     */
    private String apiKeyBySystem;

    /**
     * 访问授权接口的认证 Token
     */
    //private String authToken;
    public OpenAiInterceptor(String apiKeyBySystem) {
        this.apiKeyBySystem = apiKeyBySystem;
    }




    @NotNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        // 1. 获取原始url
        Request original = chain.request();

        // 2. 从url中读取apiKey, 优先使用用户传递的apiKey
        String apiKeyByHeader = original.header("apiKey");
        String apikey = (null == apiKeyByHeader ? apiKeyBySystem : apiKeyByHeader);

        // 3. 重新构建请求
        Request request = original.newBuilder()
                .url(original.url())
                // 设置认证授权头
                .header(Header.AUTHORIZATION.getValue(), "Bearer " + apikey)
                // 设置内容类型头
                .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
                // 设置请求方法和请求体
                .method(original.method(), original.body())
                .build();

        // 4. 返回应答结果
        return chain.proceed(request);
    }



}
